package com.ruoyi.uitity;
import com.alibaba.fastjson2.JSON;
import com.rabbitmq.client.Channel;
import com.ruoyi.domain.T06;
import com.ruoyi.domain.T21;
import com.ruoyi.domain.Wxmessage;
import com.ruoyi.framework.config.RabbitConfig;
import com.ruoyi.service.IT06Service;
import com.ruoyi.service.IT21Service;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.SendTo;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.*;

@Component
@Slf4j
public class WxMessageConsumer {

    @Autowired
    private BaiduChatBot baiduChatBot;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private IT06Service t06Service;

    @Autowired
    private IT21Service t21Service;

    // 添加线程池
    private final ExecutorService executor = new ThreadPoolExecutor(
            20, // 核心线程数
            20, // 最大线程数
            60L, TimeUnit.SECONDS, // 空闲线程存活时间
            new LinkedBlockingQueue<>(50), // 阻塞队列
            new ThreadPoolExecutor.CallerRunsPolicy() // 拒绝策略
    );

    @RabbitListener(queues = RabbitConfig.QUEUE_NAME)
    @SendTo()
    public String receiveMessage(String message, Channel channel, Message msg, CorrelationData correlationId) throws IOException {
        long deliveryTag = msg.getMessageProperties().getDeliveryTag();
        Future<String> future = executor.submit(() -> {
            try {
                Map<String, Object> map = JSON.parseObject(message, Map.class);
                Object userIdObj = map.get("userId");
                Long userId;
                if (userIdObj instanceof Integer) {
                    userId = ((Integer) userIdObj).longValue();
                } else if (userIdObj instanceof Long) {
                    userId = (Long) userIdObj;
                } else {
                    throw new IllegalArgumentException("Invalid type for 'userId': " + (userIdObj == null ? "null" : userIdObj.getClass().getName()));
                }
                initbaiduChatBot(userId);
                String result = BaiduChatBot.createConversation((String) map.get("msg"));

                return result;
            } catch (Exception e) {
                throw e;
            }
        });

        try {
            String result = future.get(); // 获取线程池任务的结果
            channel.basicAck(deliveryTag, false);
            return result;
        } catch (Exception e) {
            try {
                channel.basicNack(deliveryTag, false, true);
            } catch (IOException ioException) {
                log.error("消息确认失败: {}", ioException.getMessage(), ioException);
            }
            return null;
        }
    }

    public void initbaiduChatBot(Long userID) {
        T06 t06 = t06Service.selectT06ByF0601(userID);
        T21 t21 = t21Service.selectT21ByF0301AndDelFlag(t06.getF0301(), "0");
        baiduChatBot.init(t21.getF2103(), t21.getF2104());
    }

    @PreDestroy
    public void destroy() {
        executor.shutdown();
        try {
            if (!executor.awaitTermination(60, TimeUnit.SECONDS)) {
                executor.shutdownNow();
            }
        } catch (InterruptedException e) {
            executor.shutdownNow();
            Thread.currentThread().interrupt();
        }
    }
}
